<template>
  <el-dialog
    class="distribute-contract-dialog"
    width="1400px"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    v-dialogDrag="true"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <template slot="title">
      <span class="el-dialog__title">派发合同</span>
    </template>

    <el-form
      ref="distributeContractForm"
      :model="formData"
      :rules="formRules"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="单位名称:" prop="entrustOrganizationId">
            <el-input v-model="formData.organizationName" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同编号:" prop="agreementNumber">
            <el-input v-model="formData.agreementNumber" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人:" prop="contactsName">
            <el-input v-model="formData.contactsName" disabled>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="联系电话:" prop="contactsMobile">
            <el-input v-model="formData.contactsMobile" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="单位地址:" prop="organizationAddress">
            <el-input v-model="formData.organizationAddress" disabled>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div style="color: #252d57; font-weight: bold; font-size: 17px; padding-left: 0px;">
        <span>检测清单</span>
        <el-button
          style="float: right;"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAddEquipment"
        >添行</el-button>
      </div>
      <el-table style="margin-top: 15px;" :data="formData.tasksContractEquipmentList">
        <el-table-column label="序号" type="index" align="center" width="50" />
        <el-table-column label="设备名称" align="center" min-width="200">
          <template slot="header">
            <span style="color: red;">*</span>
            <span>设备名称</span>
          </template>
          <template slot-scope="scope">
            <el-autocomplete
              class="query-organization-autocomplete"
              style="width: 100%;"
              v-model="scope.row.entrustEquipmentName"
              :fetch-suggestions="equipmentNameFetchSuggestions"
              placeholder="请输入"
              value-key="label"
              placement="bottom"
              :popper-append-to-body="false"
              @select="handleEquipmentSelect($event, scope.row)"
            ></el-autocomplete>
            <!-- <el-select
              v-model="scope.row.entrustEquipmentId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              size="mini"
              filterable
              clearable
              @change="handleEquipmentChange($event, scope.row)"
            >
              <el-option
                v-for="(item, index) in entrustEquipmentList"
                :key="index"
                :label="item.equipmentName"
                :value="item.equipmentId"
              ></el-option>
            </el-select> -->
          </template>
        </el-table-column>
        <el-table-column label="设备类型" align="center" min-width="150">
          <template slot="header">
            <span style="color: red;">*</span>
            <span>设备类型</span>
          </template>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.entrustEquipmentTypeCode"
              placeholder="请选择"
              style="width: 100%"
              size="mini"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in entrustEquipmentTypeList"
                :key="index"
                :label="item.name"
                :value="item.equipmentTypeCode"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="规格及型号" align="center" prop="specificationModel" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.specificationModel }}
          </template>
        </el-table-column>
        <el-table-column label="生产厂家" align="center" prop="manufacturerName" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.manufacturerName }}
          </template>
        </el-table-column>
        <el-table-column label="使用场所" align="center" prop="radiationSite" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.radiationSite }}
          </template>
        </el-table-column>
        <el-table-column label="购买时间" align="center" min-width="100">
          <template slot-scope="{ row }">
            {{ parseTime(row.purchaseTime, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="检测类别" align="center" prop="inspectionTypeId" min-width="100">
          <template slot="header">
            <span style="color: red;">*</span>
            <span>检测类别</span>
          </template>
          <template slot-scope="scope">
            <div style="text-align: left;">
              <el-checkbox v-model="scope.row.checkboxInspecId" label="3">防护检测</el-checkbox>
              <br />
              <el-radio-group v-model="scope.row.radioInspecId">
                <el-radio style="margin-right: 0px;" label="5">验收检测</el-radio><br />
                <el-radio style="margin-right: 0px;" label="2">状态检测</el-radio><br />
                <el-radio style="margin-right: 0px;" label="4">稳定性检测</el-radio>
              </el-radio-group>
              <el-checkbox v-model="scope.row.checkboxInspecId2" label="9">环境检测</el-checkbox>
              <div v-if="scope.row.radioInspecId == 4">
                稳定性周期:
                <el-select style="width: 100px;" v-model="scope.row.stabilityCycle">
                  <el-option
                    v-for="item in dict.type.stability_cycle"
                    :key="item.value"
                    :label="item.label"
                    :value="Number(item.value)"
                  ></el-option>
                </el-select>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="检测项目" align="center" prop="inspectionCategory" width="150">
          <template slot-scope="{ row }">
            {{ row.inspectionCategory }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="70">
          <template slot-scope="scope">
            <el-button style="color: #f32d2d" type="text" @click="handleRemoveEquipment(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; margin-bottom: 15px; color: #252d57; font-weight: bold; font-size: 17px; padding-left: 0px;">
        <span>任务信息</span>
      </div>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="要求完成日期" prop="personalDosimeterRequireCompletionDate">
            <el-date-picker
              style="width: 100%"
              v-model="formData.personalDosimeterRequireCompletionDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :picker-options="{
                disabledDate: (time) =>
                  time.getTime() <
                  new Date(new Date().setHours(0, 0, 0, 0)),
              }"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务指派人" prop="taskAssignor" label-width="100px">
            <el-select
              style="width: 100%"
              v-model="formData.taskAssignor"
              placeholder="请选择"
              :filterable="true"
              :multiple="true"
              :clearable="true"
            >
              <el-option
                v-for="(item, index) in assignorList"
                :key="index"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="dialog-footer" slot="footer">
      <el-button style="margin-right: 50px;" type="primary" @click="handleConfirm(true)">派发</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { entrustOrganizationDetail } from '@/api/person/entrustOrganization'
import { entrustEquipmentListing } from '@/api/person/entrustEquipment'
import { entrustEquipmentTypeListing } from '@/api/person/entrustEquipmentType'
import { getAssignorList } from '@/api/slides/detectionTogether'
import { detectionTogetherAssign2 } from '@/api/slides/detectionTogether'

export default {
  name: 'DistributeContractDialog',
  components: {},
  dicts: ['stability_cycle'],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: () => ({})
    },
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    }
  },
  data() {
    return {
      entrustEquipmentList: [],
      entrustEquipmentTypeList: [],
      assignorList: [],
      formData: {},
      formRules: {
        entrustOrganizationId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        agreementNumber: [],
        contactsName: [],
        contactsMobile: [],
        organizationAddress: [],
        tasksContractEquipmentList: [],
        personalDosimeterRequireCompletionDate: [],
        taskAssignor: [],
      },
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      this.formData.entrustOrganizationId = this.row.entrustOrganizationId
      this.formData.organizationName = this.row.organizationName
      this.formData.agreementId = this.row.agreementId
      this.formData.agreementNumber = this.row.agreementNumber
      this.getEntrustOrganizationDetail()
      this.getEntrustEquipmentList()
      this.getEntrustEquipmentTypeList()
      this.getAssignorList()
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.initFormData()
      this.$refs.distributeContractForm.resetFields()
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        entrustOrganizationId: '',
        organizationName: '',
        agreementId: '',
        agreementNumber: '',
        contactsName: '',
        contactsMobile: '',
        organizationAddress: '',
        tasksContractEquipmentList: [],
        personalDosimeterRequireCompletionDate: '',
        taskAssignor: [],
      }
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      data.tasksContractEquipmentList.forEach(item => {
        const findRes = this.entrustEquipmentList.find(equ => equ.equipmentName == item.entrustEquipmentName)
        item.entrustEquipmentId = findRes ? findRes.equipmentId : ''

        if (item.checkboxInspecId && item.radioInspecId) {
          item.inspectionTypeId = '3,' + item.radioInspecId
        } else if (item.checkboxInspecId) {
          item.inspectionTypeId = '3'
        } else if (item.radioInspecId) {
          item.inspectionTypeId = item.radioInspecId
        }

        if (item.checkboxInspecId2) {
          item.inspectionTypeId += ',9'
        }
      })
      data.taskAssignor = data.taskAssignor?.join(',')
      return data
    },
    // 获取委托单位详情信息
    getEntrustOrganizationDetail() {
      entrustOrganizationDetail(this.formData.entrustOrganizationId).then(res => {
        this.formData.contactsName = res.data.contactsName
        this.formData.contactsMobile = res.data.contactsMobile
        this.formData.organizationAddress = res.data.addressDetails
      }).catch(err => {})
    },
    // 根据单位获取设备列表
    getEntrustEquipmentList() {
      const params = {
        entrustOrganizationId: this.formData.entrustOrganizationId,
      }
      entrustEquipmentListing(params).then(res => {
        this.entrustEquipmentList = res.data || []
        this.entrustEquipmentList.forEach(item => {
          item.label = `${item.equipmentName}（${item.equipmentNumber || '暂无设备编号'}）`
        })
      }).catch(err => {})
    },
    // 获取设备类型下拉框
    getEntrustEquipmentTypeList() {
      entrustEquipmentTypeListing().then(res => {
        this.entrustEquipmentTypeList = res.data || []
      }).catch(err => {})
    },
    // 获取派发人下拉框
    getAssignorList() {
      getAssignorList().then(res => {
        this.assignorList = res.data || []
      }).catch(err => {})
    },
    // 添加检测设备
    handleAddEquipment() {
      this.formData.tasksContractEquipmentList.push({
        entrustEquipmentId: '',
        entrustEquipmentName: '',
        entrustEquipmentTypeCode: '',
        checkboxInspecId: '',
        checkboxInspecId2: '',
        radioInspecId: '',
      })
    },
    // 移除检测设备
    handleRemoveEquipment(index) {
      this.formData.tasksContractEquipmentList.splice(index, 1)
    },
    // 设备名称输入建议数据
    equipmentNameFetchSuggestions(queryString, callback) {
      const results = this.entrustEquipmentList.filter(item => item.equipmentName.indexOf(queryString) > -1)
      callback(results.length > 0 ? results : this.entrustEquipmentList)
    },
    // 选择的设备改变时
    handleEquipmentSelect(item, row) {
      row.entrustEquipmentId = item.equipmentId
      this.handleEquipmentChange(item.equipmentId, row)
    },
    // 选择的设备改变时
    handleEquipmentChange(value, row) {
      const findRes = this.entrustEquipmentList.find(item => item.equipmentId == value)
      row.entrustEquipmentName = findRes ? findRes.equipmentName : ''
      row.entrustEquipmentTypeCode = findRes ? findRes.entrustEquipmentTypeCode : ''
      row.specificationModel = findRes ? findRes.specificationModel : ''
      row.manufacturerName = findRes ? findRes.manufacturerName : ''
      row.radiationSite = findRes ? findRes.radiationSite : ''
      row.purchaseTime = findRes ? findRes.purchaseTime : ''
      row.largeCategory = findRes ? findRes.largeCategory : ''
      if (findRes && findRes.equipmentName.indexOf('个人剂量') != -1) {
        row.inspectionCategory = 'X/γ射线外照射个人剂量检测'
      }
      row.checkboxInspecId = ''
      row.checkboxInspecId2 = ''
      row.radioInspecId = ''
    },
    // 点击派发
    handleConfirm() {
      this.$refs.distributeContractForm.validate(valid => {
        if (!valid) return

        // if (this.formData.tasksContractEquipmentList.length == 0) {
        //   this.$modal.msgWarning('请添加检测设备')
        //   return
        // }
        let valid2 = true
        this.formData.tasksContractEquipmentList.forEach(item => {
          if (!item.entrustEquipmentName) {
            this.$modal.msgWarning('设备名称不能为空')
            valid2 = false
            return
          }
          if (!item.entrustEquipmentTypeCode) {
            this.$modal.msgWarning('设备类型不能为空')
            valid2 = false
            return
          }
          if (!item.checkboxInspecId && !item.radioInspecId && !item.checkboxInspecId2) {
            this.$modal.msgWarning('请选择检测类别')
            valid2 = false
            return
          }
        })
        if (!valid2) return

        const data = this.getFormData()
        detectionTogetherAssign2(data).then(res => {
          this.$message.success('派发成功')
          this.dialogVisible = false
          this.$emit('refresh')
        }).catch(err => {})
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.distribute-contract-dialog {

  ::v-deep .el-dialog__body {
    max-height: 85vh;
    overflow-y: auto;
  }

  .query-organization-autocomplete {

    ::v-deep .el-autocomplete-suggestion {
      width: auto !important;
    }
  }
}
</style>
